package com.putao.album.child;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.bean.Child;
import com.putao.album.dialog.ConfirmDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.fileupload.FileUploadState;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.BitmapHelper;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.SharedPreferencesHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-4-29.
 */
public class ActivityChildManager extends BaseActivity {
    private ListView mListView;
    private ArrayList<Child> mDates = new ArrayList<Child>();

    private ActivityChildManagerAdapter mAdapter;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_child_manager;
    }

    @Override
    public void doInitSubViews(View view) {
        TextView title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.child_manager_title);
        Button right_btn = (Button) findViewById(R.id.right_btn);
        right_btn.setVisibility(View.INVISIBLE);

        mListView = (ListView) findViewById(R.id.list_child);

        View add_child_btn_view = LayoutInflater.from(mContext).inflate(R.layout.activity_child_manager_add_btn, null);
        mListView.addFooterView(add_child_btn_view);

        mAdapter = new ActivityChildManagerAdapter();
        mListView.setAdapter(mAdapter);
        queryViewById(R.id.empty_invite_baby_btn, true);
        addOnClickListener(R.id.back_btn, R.id.btn_add_child);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Bundle bundle = new Bundle();
                Child child = mAdapter.getItem(i);
                bundle.putString("child_id", child.getId());
                ActivityHelper.startActivity(mActivity, ActivityChildDetail.class, bundle);
            }
        });

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Child child = mAdapter.getItem(position);
                showConfigCancelDialog(child);
                return true;
            }
        });

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void doInitData() {
        startGetBabyList();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.btn_add_child:
                ActivityHelper.startActivity(mActivity, ActivityChildAdd.class);
                break;
            case R.id.empty_invite_baby_btn:
                ActivityHelper.startActivity(mActivity, ActivityChildConnect.class);
                break;
        }
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_ADD_CHILD_SUCCESS:
                startGetBabyList();
                break;
            case PuTaoConstants.EVENTBUS_UPLOAD_PHOTOS:
                Bundle bundle = event.bundle;
                String status = bundle.getString("status");
                if (FileUploadState.START.equals(status)) {
                    mActivity.finish();
                }
                break;
        }
    }

    /**
     * 取消关联确认
     *
     * @param child
     */
    private void showConfigCancelDialog(final Child child) {

        new ConfirmDialogBuilder(mContext)
                .setMessage("取消对\""+child.getName()+"\"的关注后,\n" +
                        "你将不能看到\""+child.getName()+"\"的照片")
                .setPositiveButton("不了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setNegativeButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        CancelConnect(child);
                    }
                })
                .Create()
                .show();
    }

    /**
     * 取消关联的宝宝
     *
     * @param child
     */
    private void CancelConnect(final Child child) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("baby_id", child.getId());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_BABY_CANCEL,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                mDates.remove(child);
                                mAdapter.notifyDataSetChanged();
                                if (mDates.size() == 0) {
                                    SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_BABY_ID, PuTaoConstants.DEVAULT_BABY_ID);
                                    EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_DELETE_LAST_CHILD));
                                } else {
                                    EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_DELETE_CHILD));
                                }
                            }
                            String msg = json.getString("msg");
                            showToast(msg);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });


    }

    private void startGetBabyList() {
        HashMap<String, String> params = new HashMap<String, String>();

        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_USER_BABYLIST,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });


    }

    private void doAnalyzeDataList(JSONObject data) {
        mDates.clear();
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String baby_id = o.optString("baby_id");
                    String name = o.optString("name");
                    String avatar = o.optString("avatar");
                    Child item = new Child();
                    item.setId(baby_id);
                    item.setName(name);
                    item.setAvatar(avatar);
                    mDates.add(item);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private class ActivityChildManagerAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mDates != null) {
                return mDates.size();
            }
            return 0;
        }

        @Override
        public Child getItem(int i) {
            return mDates.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder = new ViewHolder();
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.activity_child_manager_item, null);
                holder.icon = (ImageView) view.findViewById(R.id.icom);
                holder.name = (TextView) view.findViewById(R.id.name);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            String name = getItem(i).getName();
            if (name != null) {
                holder.name.setText(name);
            }

            String icon_path = getItem(i).getAvatar();
            if (icon_path != null) {
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                        .cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
                        .considerExifParams(true)
                        .build();
                ImageLoader.getInstance().displayImage(icon_path, holder.icon, options);
            }

            return view;
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }

        class ViewHolder {
            public ImageView icon;
            public TextView name;
        }
    }
}
